package com.hyzx.qbasic.admin.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Optional;
import java.util.concurrent.*;

/**
 * Created by 黄江华 on 2017/9/20.
 * 使用线程池管理线程，避免通过new Thread创建新线程
 */

public class ThreadPoolUtils {
    private static final Logger logger = LoggerFactory.getLogger(ThreadPoolUtils.class);

    private static ExecutorService threadPool = new ThreadPoolExecutor(
            Runtime.getRuntime().availableProcessors(),
            100,
            60L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(10000));

    /**
     * 不需要返回值，不需要等待执行结果的异步任务
     */
    public static void execute(Runnable task) {
        try {
            threadPool.execute(task);
        } catch (Exception ex) {
            logger.error("ThreadPoolUtils.execute方法异常", ex);
        }
    }

    /**
     * 需要返回值，需要等待执行结果的异步任务
     */
    public static <T> Optional<Future<T>> submit(Callable<T> task) {
        try {
            return Optional.of(threadPool.submit(task));
        } catch (Exception ex) {
            logger.error("ThreadPoolUtils.submit方法异常", ex);
        }

        return Optional.empty();
    }
}
